<template>
  <el-dialog
    top="10vh"
    width="700px"
    title="添加/编辑"
    :visible.sync="dialogValue"
    :close-on-click-modal="false"
    append-to-body
  >
    <SubmitForm
        :rule-form="ruleForm"
        :rules="rules"
        :form-list="formList"
        @change="handleFormChange"
        @save="onSave"
        @close="dialogValue = false"
    >
      <template v-slot:options>
        <el-form inline v-for="(item,index) in options" label-position="top">
          <el-form-item label="序号">
            <el-input v-model="item.sort"  style="width: 50px"/>
          </el-form-item>
          <el-form-item label="名称">
            <el-input v-model="item.name" style="width: 360px"/>
          </el-form-item>
          <el-form-item label="值">
            <el-input v-model="item.value" style="width: 80px"/>
          </el-form-item>
          <el-form-item label="是否答案">
            <el-switch :value="item.is_correct" :active-value="1" :in-active-value="0" @change="(val) => handleChangeCorrect(val, item)"/>
          </el-form-item>
          <el-form-item label="操作">
            <div style="margin-top: 3px">
              <i  class="el-icon-circle-plus-outline" style="font-size: 24px;color: #3CAA49;margin-right: 10px;cursor:pointer;" @click="addOption(item)"></i>
              <i  class="el-icon-remove-outline" style="font-size: 24px;color: #3CAA49;cursor:pointer;"  @click="deleteOption(index)"></i>
            </div>
          </el-form-item>
        </el-form>
      </template>
    </SubmitForm>
  </el-dialog>
</template>

<script>
import { http } from '@/api'
export default {
  name: 'FormAdd',
  computed: {
    disabled() {
      if (this.ruleForm.id) {
        return false
      }
      return true
    }
  },
  data() {
    return {
      tabName: 'detail',
      apiKey: 'question',
      dialogValue: false,
      ruleForm: {
      },
      defaultForm: {
        type: 'single_choice'
      },
      rules: {
        category_id: [{ required: true, message: '不能为空' }],
        name: [{ required: true, message: '不能为空' }],
      },
      formList: [
        {
          key: 'category_id',
          name: 'select',
          label: '所属分类',
          colSpan: 12,
          options: [],
        },
        {
          key: 'type',
          name: 'select',
          label: '类型',
          colSpan: 12,
          options: [
            { name: '单选', value: 'single_choice' },
            { name: '多选', value: 'multiple_choice' },
          ],
        },
        // {
        //   key: 'course_id',
        //   name: 'select',
        //   label: '所属课程',
        //   colSpan: 12,
        //   options: []
        // },
        {
          key: 'name',
          name: 'input',
          type: 'textarea',
          label: '题目名称',
          colSpan: 24
        },
        // {
        //   key: 'sort',
        //   name: 'input',
        //   label: '排序',
        //   colSpan: 12
        // },
        {
          name: 'title',
          label: '答案',
          colSpan: 24
        },
        {
          key: 'options',
          label: '',
          colSpan: 24
        },

        {
          key: 'status',
          name: 'switch',
          label: '是否发布',
          activeValue: 1,
          inactiveValue: 0,
          colSpan: 24
        }
      ],
      options: [
      ]
    }
  },
  methods: {
    handleFormChange({ key, val }) {
      if (key === 'type') {
        if (val === 'single_choice') {
          this.options.forEach((el,_index) => {
            el.is_correct = 0
          })
        }
      } else if (key === 'category_id') {
        // http.course.list({ category_id: val }).then(res => {
        //   this.formList[1].options = res.data.map(el => ({ name: el.name, value: el.id }))
        // })
      }
    },
    open(row) {
      this.dialogValue = true
      http.category.list().then(res => {
        this.formList[0].options = res.data.map(el => ({ name: el.name, value: el.id }))
      })
      if (row) {
        http[this.apiKey].read(row.id).then(res => {
          this.ruleForm = {
            ...res.data
          }
          // if (this.ruleForm.category_id) {
          //   http.course.list({ category_id: this.ruleForm.category_id }).then(res => {
          //     this.formList[1].options = res.data.map(el => ({ name: el.name, value: el.id }))
          //   })
          // }
        })
        http.questionOption.list({ question_id: row.id }).then(res => {
          this.options = res.data.map(el => ({ ...el }))
        })
      } else {
        this.ruleForm = {
          ...this.defaultForm
        }
        this.options = [
          {
            id: undefined,
            sort: 0,
            name: '',
            value: '',
            is_correct: 0
          },
        ]
      }
    },
    onSave() {
      if (this.options.length < 2) {
        this.$message.error('至少添加两个答案选项')
        return
      }
      for (const element of this.options) {
        const option = element
        if (!option.name || !option.value) {
          this.$message.error('选项名称和值不能为空')
          return
        }
      }
      let isCorrect = this.options.some(item => item.is_correct === 1)
      if (!isCorrect) {
        this.$message.error('请设置正确答案')
        return
      }
      http[this.apiKey][this.ruleForm.id ? 'update' : 'create'](this.ruleForm.id, {
        ...this.ruleForm,
        options: this.options
      }).then(res => {
        this.$message.success('操作成功')
        this.dialogValue = false
        this.$emit('get-page')
      })

    },
    addOption() {
      this.options.push({
        id: undefined,
        sort: 0,
        name: '',
        value: '',
        is_correct: 0
      })
    },
    async deleteOption(index) {
      if (this.options.length === 2) {
        this.$message.error('至少保留两个选项')
        return
      }
      this.$confirm('确定删除该选项吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        if (this.options[index].id) {
          await http.questionOption.delete(this.options[index].id)
        }
        this.options.splice(index, 1)
        this.$message.success('删除成功')
      }).catch(() => {
      })
    },
    handleChangeCorrect(val, item) {
      console.log(val)
      if (val === 1) {
        if (this.ruleForm.type === 'single_choice') {
          this.options.forEach((el,_index) => {
            el.is_correct = 0
          })
        }
      }
      item.is_correct = val
    }
  }
}
</script>

<style scoped lang="scss">
</style>
